﻿using System.Collections.Generic;
using System.Linq;
using Missbot.Common;
using Missbot.Core.Cache;
using Dolany.UtilityTool;
using Missbot.Core.CrossingRoute;
using Newtonsoft.Json;

namespace Missbot.AIModule.Gaming.Gift
{
    /// <summary>
    /// 礼物服务
    /// </summary>
    public class GiftSvc : IDataMgr, ISingleton, IViewable, IExchangable
    {
        /// <summary>
        /// 所有礼物物品
        /// </summary>
        public List<GiftItem> GiftList { get; set; }

        public GiftItem this[string GiftName] => GiftList.FirstOrDefault(p => p.Name == GiftName);

        /// <summary>
        /// 今日礼物商店售卖的商品
        /// </summary>
        public IEnumerable<GiftItem> SellingGifts
        {
            get
            {
                const string Key = "SellingGifts";
                var record = GlobalVarDA.Get(Key);
                if (record != null)
                {
                    var giftNames = JsonConvert.DeserializeObject<List<string>>(record.Value);
                    return GiftList.Where(p => giftNames != null && giftNames.Contains(p.Name)).ToList();
                }

                var gifts = RandomGifts(7);
                record = new GlobalVarRecord
                {
                    Key = Key,
                    Value = JsonConvert.SerializeObject(gifts),
                    ExpiryTime = CommonUtil.UntilTommorow()
                };
                record.Insert();

                return GiftList.Where(p => gifts.Contains(p.Name)).ToList();
            }
        }

        /// <summary>
        /// 获取随机礼物
        /// </summary>
        /// <param name="count"></param>
        /// <returns></returns>
        private List<string> RandomGifts(int count)
        {
            return Rander.RandSort(GiftList.Select(p => p.Name).ToArray()).Take(count).ToList();
        }

        public void RefreshData()
        {
            GiftList = GiftItemDA.GetAll();
        }

        public (bool canView, string viewCommand) ViewableCheck(string name)
        {
            return this[name] != null ? (true, "查看礼物") : (false, null);
        }

        public (bool canExchange, string exchangeCommand) ExchangableCheck(string name)
        {
            return this[name] != null ? (true, "兑换礼物") : (false, null);
        }
    }
}